package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.ca.ridersclubapplication.adapter.HomePagerAdapter;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.Token;
import com.ca.ridersclubapplication.fragment.FoundFragment;
import com.ca.ridersclubapplication.fragment.MainFragment;
import com.ca.ridersclubapplication.fragment.MessageFragment;
import com.ca.ridersclubapplication.fragment.MyFragment;
import com.ca.ridersclubapplication.fragment.RefreshableFragment;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.MessageRequester;
import com.ca.ridersclubapplication.service.MessageService;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.TransitionUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.MainTitleBar;
import com.ca.ridersclubapplication.view.button.MainFooterButton;

import java.util.ArrayList;
import java.util.List;

import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends ImmersiveActivity {

    private static int titleCLHeight;

    //  将主页按钮设置回到顶部Icon标志
    private static boolean canToTop = false;


    private static ViewPager2 pager;
    private HomePagerAdapter adapter;

    private ConstraintLayout titleCL;
    private MainTitleBar titleBar;

    private MainFragment mainFragment;
    private FoundFragment foundFragment;
    private MessageFragment messageFragment;
    private MyFragment myFragment;


    private CallbackView loginCallbackView;


    private SwipeRefreshLayout refresh;

    private static final List<RefreshableFragment> fragmentList = new ArrayList<>();
    private static final List<MainFooterButton> buttonList = new ArrayList<>();

    private TextView dotTargetView;

    //  未读圆点
    private Badge badge;

    //  消息服务
    private Intent messageServiceIntent;


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //  初始化视图
        initView();

        //  设置监听器
        initListener();

        //  请求数据
        loadData();

        //  开启消息服务
        messageServiceIntent = new Intent(this, MessageService.class);
        startService(messageServiceIntent);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void initView() {

        //  标题栏（头像 + 搜索栏 + 通知按钮）
        titleCL = findViewById(R.id.cl_mainTitle);
        titleBar = findViewById(R.id.bar_mainTitle);

        //  标题栏头像需要登录后才能显示，因此放入数据处理器中
        loginCallbackView = new CallbackView() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void update() {
                Handleable data = DataHandler.getData("Login");
                if (data instanceof BooleanEntity) {
                    boolean isLogin = ((BooleanEntity) data).getValue();
                    if (isLogin) {
                        Token token = DataHandler.getToken(MainActivity.this);
                        titleBar.setHeaderUrl(FileRequester.HEADER_BY_ID_BASE_URL + token.getId());

                        //  开启消息服务
                        messageServiceIntent = new Intent(MainActivity.this, MessageService.class);
                        startService(messageServiceIntent);

                        //  请求消息列表
                        messageFragment.refresh();
                    }
                    else {
                        titleBar.headerView.setImageDrawable(getResources().getDrawable(R.drawable.ic_error_image));
                        //  停止消息服务
                        if (messageServiceIntent != null) {
                            stopService(messageServiceIntent);
                        }

                        //  清除消息列表
                        messageFragment.clearMsgList();

                        //  清除个人主页数据
                        myFragment.clearData();
                    }
                }
            }
        };
        DataHandler.putView("Login", loginCallbackView);

        //  ViewPager2视图（四个页面）
        pager = findViewById(R.id.pager);
        adapter = new HomePagerAdapter(this);
        //  添加首页面
        mainFragment = new MainFragment(titleCL, titleBar);
        adapter.addFragment(mainFragment);
        fragmentList.add(mainFragment);
        //  添加发现页面
        foundFragment = new FoundFragment();
        adapter.addFragment(foundFragment);
        fragmentList.add(foundFragment);
        //  添加消息页面
        messageFragment = new MessageFragment();
        adapter.addFragment(messageFragment);
        fragmentList.add(messageFragment);
        //  添加我的页面
        myFragment = new MyFragment();
        adapter.addFragment(myFragment);
        fragmentList.add(myFragment);

        //  设置ViewPager2
        pager.setAdapter(adapter);
        pager.setUserInputEnabled(false);

        //  添加底部按钮（首页、发现、消息、我）
        MainFooterButton homeButtom = findViewById(R.id.btn_home);
        buttonList.add(homeButtom);
        buttonList.add(findViewById(R.id.btn_found));
        buttonList.add(findViewById(R.id.btn_message));
        buttonList.add(findViewById(R.id.btn_account));

        //  首页按钮设置指定Icon
        homeButtom.setOtherIcon(getResources().getDrawable(R.drawable.ic_top));

        //  下拉刷新控件
        refresh = findViewById(R.id.refresh);
        //设置加载动画背景颜色
        refresh.setProgressBackgroundColorSchemeColor(getResources().getColor(android.R.color.background_light));
        //设置进度动画的颜色
        refresh.setColorSchemeResources(
                R.color.primary,
                R.color.warning,
                R.color.danger);

        //  获取标题栏高度
        titleBar.post(() -> {
            titleCLHeight = titleCL.getHeight();
        });

        //  未读消息圆点
        dotTargetView = findViewById(R.id.dot_target);
        badge = new QBadgeView(this)
                .bindTarget(dotTargetView)
                .setBadgeNumber(0)
                .setBadgeTextSize(8, true)
                .setExactMode(false)
                .setShowShadow(true)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int i, Badge badge, View view) {
                        if (Badge.OnDragStateChangedListener.STATE_SUCCEED == i) {
                            //  消除所有未读消息
                            MessageRequester.setReadAll(MainActivity.this, null);
                        }
                    }
                });

        //  为消息按钮添加小红点回调视图
        DataHandler.putView("HasNewMsg", new CallbackView() {
            @Override
            public void update() {
                badge.setBadgeNumber(MessageService.unReadCount);
                if (messageFragment != null) {
                    messageFragment.setReadAll();
                }
            }
        });

        Long accountId = DataHandler.getToken(this).getId();
        DataHandler.putView("AccountUpdateDto:" + accountId, new CallbackView() {
            @Override
            public void update() {
                ImageUtils.loadCircleImage(MainActivity.this, FileRequester.HEADER_BY_ID_BASE_URL + accountId, titleBar.headerView);
            }
        });
    }

    private void initListener() {

        //  设置ViewPage2页面改变事件监听
        //  当页面改变时，同时改变底部按钮样式
        pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            private int lastPosition = 0;

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                buttonList.get(lastPosition).second();

                //  如果回到主页，则根据canToTop设置主页按钮
                if (position == 0 && canToTop) {
                    showToTopIcon(true);
                }
                else {
                    buttonList.get(position).primary();
                }
                lastPosition = position;
                int h = (int) (pager.getMeasuredWidth() * (5.5/ 8));
                if (position == 0 && MainFragment.getY() < h) {
                    titleCL.setBackgroundColor(getResources().getColor(R.color.transparent));
                    titleBar.light();
                }
                else {
                    titleCL.setBackgroundColor(getResources().getColor(R.color.base_background));
                    titleBar.dark();
                }

                //  设置标题栏是否可见
                if (position == 3) {
                    titleBar.setVisibility(View.GONE);
                    titleBar.setAlpha(0);
                    myFragment.showMiniTitle();
                }
                else if (titleBar.getVisibility() == View.GONE) {
                    TransitionUtils.fadeInView(titleBar);
                    myFragment.showMiniTitle();
                }

                //  如果为发现页面，则禁用下拉刷新
                refreshIsEnable(position != 1);

                //  页面变动后，将下拉刷新关闭
                stopRefreshing();
            }
        });

        //  按钮点击事件，点击跳转到指定的页面
        for (int i = 0; i < buttonList.size(); i++) {
            MainFooterButton button = buttonList.get(i);
            final int position = i;
            button.setOnClickListener(v -> {
                //  判断是否为消息、我按钮，未登录的情况下，点击跳转至登录Activity
                if (!DataHandler.isLogin(this) && position > 1) {
                    //  启动到登录Activity
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("clickIndex", position);
                    startActivity(intent);
                }
                else if (position == 0 && pager.getCurrentItem() == 0 && canToTop) {
                    //  回到顶部
                    canToTop = false;
                    mainFragment.goToTop();
                }
                else {
                    pager.setCurrentItem(position);
                }
            });
        }

        //  头像点击，启动AccountActivity
        titleBar.headerView.setOnClickListener(v -> {

            //  如果用户没有登录，则启动登录Activity
            if (!DataHandler.isLogin(this)) {
                startActivity(new Intent(this, LoginActivity.class));
                return;
            }

            //  获取用户ID
            Token token = DataHandler.getToken(this);
            Intent intent = new Intent(this, AccountActivity.class);
            intent.putExtra("accountId", token.getId());
            startActivity(intent);
        });

        //  搜索框点击事件，启动搜索Activity
        titleBar.searchBar.setOnClickListener(v -> {
            Intent intent = new Intent(this, SearchActivity.class);
            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
                    Pair.create(titleBar.searchBar, "bar:search"));
            startActivity(intent, options.toBundle());
        });


        //  下拉刷新页面监听事件
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //  执行Fragment的刷新方法，停止下拉刷新动画将由各个Fragment设置
                fragmentList.get(pager.getCurrentItem()).refresh();
            }
        });
    }

    private void loadData() {

        //  设置登陆状态
        DataHandler.putData(new BooleanEntity("Login", DataHandler.isLogin(this)));
    }

    public static int getTitleCLHeight() {
        return titleCLHeight;
    }

    public static void gotoPage(int index) {
        if (pager != null) {
            pager.setCurrentItem(index);
        }
    }

    public void stopRefreshing() {
        //  停止下拉刷新动画
        refresh.setRefreshing(false);
    }

    public synchronized void showToTopIcon(boolean show) {
        MainFooterButton button = buttonList.get(0);
        if (button != null) {
            button.showOtherIcon(show);
        }
    }

    public static synchronized void canToTop(boolean flag) {
        canToTop = flag;
    }

    public void refreshIsEnable(boolean enable) {
        if (refresh != null) {
            refresh.setEnabled(enable);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataHandler.removeView("Login", loginCallbackView);
        if (messageServiceIntent != null) {
            stopService(messageServiceIntent);
        }
    }
}